package com.wgchao.amc.controller.base;

import com.wgchao.amc.autho.AuthoInfoCenter;
import com.wgchao.amc.common.BindingError;
import com.wgchao.amc.common.MenuAutho;
import com.wgchao.amc.common.PageData;
import com.wgchao.amc.common.ResultCommon;
import com.wgchao.amc.common.validate.Assign;
import com.wgchao.amc.common.validate.Save;
import com.wgchao.amc.common.validate.Update;
import com.wgchao.amc.entity.base.SysBaseRole;
import com.wgchao.amc.mapstruct.dto.SysBaseAgencyDTO;
import com.wgchao.amc.mapstruct.dto.SysBaseGroupDTO;
import com.wgchao.amc.mapstruct.dto.SysBaseRoleDTO;
import com.wgchao.amc.service.GroupService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @作者：wgchao
 * @时间：19:10 2019/10/19 0019
 * @用途：部门信息管理
 **/
@RestController
@RequestMapping("/amc/sys/base/group")
@Api(tags = "部门信息管理")
public class GroupController {
    @Autowired
    private GroupService groupService;

    @PostMapping("/save")
    @ApiOperation(value = "新增部门")
    @MenuAutho(desc = "新增部门")
    @ApiParam(name = "agencyDTO", value = "部门信息", required = true)
    public ResultCommon<SysBaseGroupDTO> save(@RequestBody @Validated(value = {Save.class}) SysBaseGroupDTO groupDTO,
                                              BindingResult bindingResult,
                                              HttpSession session) throws Exception{
        if(bindingResult.hasErrors()){
            String error = "";
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                error += (fieldError.getDefaultMessage()+",");
            }
            return ResultCommon.fail(error);
        }
        AuthoInfoCenter authoInfoCenter = AuthoInfoCenter.getInstance(session);
        return groupService.save(groupDTO, authoInfoCenter);
    }

    @GetMapping("/search/{groupId}")
    @ApiOperation(value = "根据部门ID查询部门详情")
    @MenuAutho(desc = "根据部门ID查询部门详情")
    @ApiParam(name = "groupId", value = "部门ID", required = true)
    public ResultCommon<SysBaseGroupDTO> search(@PathVariable Long groupId) throws Exception{
        return groupService.search(groupId);
    }

    @GetMapping("/search/by/{agencyCode}")
    @ApiOperation(value = "查询机构下的部门列表")
    @MenuAutho(desc = "查询机构下的部门列表")
    @ApiParam(name = "agencyCode", value = "机构编号", required = true)
    public ResultCommon<List<SysBaseGroupDTO>> search(@PathVariable String agencyCode) throws Exception{
        return groupService.search(agencyCode);
    }

    @GetMapping("/page")
    @ApiOperation(value = "分页查询部门信息，子机构以树状形式展示")
    @MenuAutho(desc = "分页查询部门信息")
    public ResultCommon<PageData<SysBaseGroupDTO>> page(int page, int limit,
                                                        @RequestParam(required = true) String agencyCode,
                                                         @RequestParam(required = false) Long groupId,
                                                         @RequestParam(required = false) String groupName,
                                                        @RequestParam(required = false) boolean child) throws Exception{
        return groupService.page(page, limit, agencyCode, groupId, groupName, child);
    }

    @PutMapping("/update")
    @ApiOperation(value = "更新部门信息", notes = "更新机构名称")
    @MenuAutho(desc = "更新部门信息")
    public ResultCommon<SysBaseAgencyDTO> update(@RequestBody @Validated(value = {Update.class}) SysBaseGroupDTO groupDTO,
                                                 BindingResult bindingResult,
                                                 HttpSession session) throws Exception{
        if(bindingResult.hasErrors()){
            String error = "";
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                error += (fieldError.getDefaultMessage()+",");
            }
            return ResultCommon.fail(error);
        }
        AuthoInfoCenter authoInfoCenter = AuthoInfoCenter.getInstance(session);
        return groupService.update(groupDTO, authoInfoCenter);
    }

    @DeleteMapping("/deletes")
    @ApiOperation(value = "删除部门信息", notes = "同时删除子部门")
    @MenuAutho(desc = "删除部门信息")
    @ApiParam(name = "groupIds", value = "部门Id列表", required = true)
    public ResultCommon deletes(@RequestBody List<Long> groupIds, HttpSession session) throws Exception{
        if(groupIds==null || groupIds.isEmpty()){
            return ResultCommon.fail("待删除部门编号缺失");
        }
        AuthoInfoCenter authoInfoCenter = AuthoInfoCenter.getInstance(session);
        return groupService.deletes(groupIds, authoInfoCenter);
    }

    @GetMapping("/search/child/list/{groupId}")
    @ApiOperation(value = "根据部门ID查询部门以及下级部门列表")
    @MenuAutho(desc = "根据部门ID查询部门以及下级部门列表")
    @ApiParam(name = "groupId", value = "部门ID", required = true)
    public ResultCommon<List<SysBaseGroupDTO>> searchChilds(@PathVariable Long groupId) throws Exception{
        return groupService.searchChilds(groupId);
    }

    @GetMapping("/search/child/tree/{groupId}")
    @ApiOperation(value = "根据部门ID查询部门以及下级部门列表(树状)")
    @MenuAutho(desc = "根据部门ID查询部门以及下级部门列表(树状)")
    @ApiParam(name = "groupId", value = "部门ID", required = true)
    public ResultCommon<SysBaseGroupDTO> searchChildsTree(@PathVariable Long groupId) throws Exception{
        return groupService.searchChildsTree(groupId);
    }


    /**********************************/
    @PutMapping("/assign/role/{groupId}")
    @ApiOperation(value = "为部门分配角色")
    @MenuAutho(desc = "为部门分配角色")
    public ResultCommon<SysBaseGroupDTO> assignedRoles(@PathVariable Long groupId,
                                                       @RequestBody @Validated(value = {Assign.class}) List<SysBaseRoleDTO> roleDTOs,
                                                       BindingResult bindingResult) throws Exception{
        String error = null;
        if((error = BindingError.error(bindingResult)) != null){
            return ResultCommon.fail(error);
        }
        return groupService.assignedRoles(groupId, roleDTOs);
    }
}
